var _ = require('lodash'),
    Q = require('q'),
    entityCollection = require('../../../Base/server/controllers/EntityCollection');
//插入装配关系
exports.createAssemblyRelation = function (assemblyRelation, completeFun) {
    var assemblyRelationEntity = entityCollection.getEntity("AssemblyRelation");
    assemblyRelationEntity.insert(assemblyRelation, function (err, newBarcodeMaster) {
        completeFun(err, newBarcodeMaster);
    });
};
//插入装配关系，如果存在则不进行插入
exports.insertIfNotExist = function (assemblyRelation) {
    var deferred = Q.defer();

    var entity = entityCollection.getEntity("AssemblyRelation");
    entity.findOne({
        BarcodeMaster: assemblyRelation.BarcodeMaster,
        AssemblyBarcode: assemblyRelation.AssemblyBarcode
    }, null, function (err, record) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询装配条码信息错误';
            newErr.message = '查询装配条码信息错误';
            deferred.reject(newErr);
            return;
        }
        if (record) {
            deferred.resolve(record);
            return;
        }
        entity.insert(assemblyRelation, function (err, newRecord) {
            if (err) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '新增装配条码信息错误';
                newErr.message = '新增装配条码信息错误';
                deferred.reject(newErr);
                return;
            }
            deferred.resolve(newRecord);
        });
    });

    return deferred.promise;
};
//删除装配关系
exports.deleteById = function (id, completeFun) {
    var assemblyRelationEntity = entityCollection.getEntity("AssemblyRelation");
    assemblyRelationEntity.deleteById(id, function (err, result) {
        completeFun(err, result);
    });
};
//查找条码的所有AssemblyType为2的数据(按时间降序)
exports.findAllByBarcodeMasterAndAssemblyType = function (barcodeMaster, completeFun) {
    var entity = entityCollection.getEntity("AssemblyRelation");
    entity.find({
        BarcodeMaster: barcodeMaster,
        AssemblyType: 2
    }, {CollectDateTime: -1}, null, function (err, record) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询装配条码信息错误';
            newErr.message = '请检查查询参数！';
            completeFun(newErr);
        } else {
            completeFun(null, record);
        }
    });
};

// 根据传入条码ID查找所有历史替换条码，按时间排序
exports.findAssemblyRelations = function (barcodeId) {
    return queryRealBarcodeMaster(barcodeId).then(function (masterInfo) {
        return queryRelationBarcodeMasters(masterInfo);
    });
};
/**
 * 通过条码ID查找装备关系
 * @param BarcodeMaster
 * @param completeFun
 */
exports.findAssemblyRelationsByBarcodeMaster = function (BarcodeMaster, completeFun) {
    var entity = entityCollection.getEntity("AssemblyRelation");
    entity.findOne({BarcodeMaster: BarcodeMaster}, [
        {
            path: 'AssemblyBarcode'
        }
    ], function (err, record) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询条码主档错误';
            newErr.message = '查询失败，请检查查询参数！';
            completeFun(newErr);
        } else {
            completeFun(null, record);
        }
    });
};

// 传入主档ID若是镭射标类型，则返回对应主档ID，否则返回原主档ID
function queryRealBarcodeMaster(barcodeId) {
    var deferred = Q.defer();

    var entity = entityCollection.getEntity("AssemblyRelation");
    entity.findOne({
        AssemblyBarcode: barcodeId,
        AssemblyType: 0
    }, null, function (err, result) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询装配关系错误';
            newErr.message = '查询装配关系失败，请检查查询参数！';
            deferred.reject(newErr);
            return;
        }
        if (!result) {
            deferred.resolve({
                barcodeMaster: barcodeId,
                isLaser: false
            });
        } else {
            deferred.resolve({
                barcodeMaster: result.BarcodeMaster,
                isLaser: true
            });
        }
    });

    return deferred.promise;
}

// 根据物料主档ID查找所有历史替换条码
function queryRelationBarcodeMasters(masterInfo) {
    var deferred = Q.defer();

    var entity = entityCollection.getEntity("AssemblyRelation");
    entity.findOne({
        $or: [{
            BarcodeMaster: masterInfo.barcodeMaster,
            AssemblyType: 2
        }, {
            AssemblyBarcode: masterInfo.barcodeMaster,
            AssemblyType: 2
        }]
    }, null, function (err, result) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询装配关系错误';
            newErr.message = '查询装配关系失败，请检查查询参数！';
            deferred.reject(newErr);
            return;
        }
        if (!result) {
            if (masterInfo.isLaser) {
                deferred.resolve([masterInfo.barcodeMaster]);
            } else {
                deferred.resolve(null);
            }
            return;
        }
        // {
        //     path: 'AssemblyBarcode',
        //     populate: [
        //         { path: 'ItemMaster', select: 'Code Name Specification ItemCategory', model: 'ItemMaster' },
        //         { path: 'MO', select: 'Code LotNumber Customer StartDateTime EndDateTime', model: 'MO' }
        //     ]
        // }
        entity.find({
            BarcodeMaster: result.BarcodeMaster,
            AssemblyType: 2
        }, {
            CollectDateTime: -1
        }, null, function (err, records) {
            if (err) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '查询装配关系错误';
                newErr.message = '查询装配关系失败，请检查查询参数！';
                deferred.reject(newErr);
                return;
            }
            var results = [];
            _.forEach(records, function (record) {
                results.push(record.AssemblyBarcode);
            });
            results.push(records[0].BarcodeMaster);
            deferred.resolve(results);
        });
    });

    return deferred.promise;
}
